package com.etlmaster.executor.scheduler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.etlmaster.executor.Job;
import com.etlmaster.executor.JobPool;
import com.etlmaster.executor.steps.scheduler.SchedulerStepMeta;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class EmJob implements org.quartz.Job {

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();

		String agentId = dataMap.getString("agentId");
		Boolean concurrencyRun = Boolean.parseBoolean(dataMap
				.getString("concurrencyRun"));
		Job job = (Job) dataMap.get("job");

		Job jobinstance = JobPool.getJob(job.getMeta().getName());
		JobPool.copyVariables(job.getSeesionId(), jobinstance.getSeesionId());
		jobinstance.setTmpJob(true);

		SchedulerStepMeta meta = (SchedulerStepMeta) dataMap.get("meta");
		String jobName = context.getJobDetail().getKey().getName();
		String invalid_date = dataMap.getString("invalid_date");
		if (invalid_date != null && invalid_date.trim().length() > 0
				&& !invalid_date.equalsIgnoreCase("null")) {
			SimpleDateFormat simeDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date date;
			try {
				date = simeDateFormat.parse(invalid_date);

				jobinstance.getVariables().put("isExpired",
						context.getNextFireTime().after(date));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		String cycle_type=dataMap.getString("cycle_type");
		String taskid = DataCollectionUtils
				.getCurrentTimestampByFormate(DataCollectionUtils.getProperties(cycle_type,"day"));
		Map<String, Object> map = new HashMap<String, Object>();
		map.putAll(job.getVariables());
		map.put("taskid", taskid);
		taskid = DpExecutorUtils.variableSubstitution(
				(String) dataMap.get("taskid"), map);
		//StepStack transstack = new StepStack("scheduleStack", 1, true);
		jobinstance.getVariables().put("jobName", jobName);
		jobinstance.getVariables().put("taskid", taskid);
		jobinstance.getVariables().put("concurrencyRun", concurrencyRun);
		jobinstance.getVariables().put("agentId", agentId);
		try {
			meta.runLoop( jobinstance, meta.getThreadNum(),"i");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
			System.exit(-1);
		}

	}

}
